package com.uinnova.product.eam.workable.listener;

import com.uinnova.product.eam.workable.model.FilterUser;
import com.uinnova.product.eam.workable.service.FilterUserService;
import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * flowable监听器，会签时多任务处理时设置多人领取任务
 *
 * @author lichong
 * @since 2022/2/25 16:32
 */
@Slf4j
@Component("generateUserByRoleListener")
public class GenerateUserByRoleListener implements ExecutionListener{

    @Value("${eam.query.user.url}")
    private String userQueryUrl;

    @Resource
    private FilterUserService filterUserService;

    @Resource
    private HttpUtil httpUtil;

    @Override
    public void notify(DelegateExecution execution) {
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String roles = currentFlowElement.getDocumentation();
        log.info("角色{}", roles);
        String users = getUserByRoleName(roles);
        Map<String, Object> variables = execution.getVariables();
        if (!StringUtils.isEmpty(users)) {
            log.info("审批用户：{}", users);
            String currentActivityId = execution.getCurrentActivityId();
            log.info("执行器id{}", execution.getCurrentActivityId());
            String processInstanceId = execution.getProcessInstanceId();
            List<String> filterUser = getFilterUser(processInstanceId, currentActivityId);
            String[] split = users.split(",");
            ArrayList<String> receiveUsers = new ArrayList<>();
            Collections.addAll(receiveUsers, split);
            variables.put("assigneeList", receiveUsers);
        }
        execution.setVariables(variables);
    }

    private String getUserByRoleName(String roleName) {
        String requestUrl = userQueryUrl+"?roleName="+roleName;
        return httpUtil.get(requestUrl,String.class);
    }

    private List<String> getFilterUser(String prcessInstanceId,String flowSequenceId){
        List<FilterUser> currentTaskAgreeUser = filterUserService.getCurrentTaskAgreeUser(prcessInstanceId, flowSequenceId);
        if(CollectionUtils.isEmpty(currentTaskAgreeUser)){
            return new ArrayList<>(0);
        }
        List<String> collect = currentTaskAgreeUser.stream().map(FilterUser::getAgreeUserCode).collect(Collectors.toList());
        return collect;
    }

}
